import 'package:chat/common/model/User.dart';
import 'package:chat/common/model/UserMessageModel.dart';
import 'package:chat/common/service/HttpService.dart';
import 'package:chat/common/utils/storage.dart';
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import '../../../common/enum/MessageType.dart';

class ChatdetailController extends GetxController {
  ChatdetailController();

  final RefreshController refreshController = RefreshController(initialRefresh: false);
  final TextEditingController textController = TextEditingController();
  final ScrollController scrollController = ScrollController();

  var userMessageList = <UserMessageModel>[].obs;
  RxInt userId = 0.obs;
  RxString userAvatar = "".obs;
  RxInt friendId = 0.obs;
  RxString friendAvatar = "".obs;
  RxString friendName = "".obs;
  RxInt targetMessageId = 0.obs;

  int pageNum = 1;
  final int pageSize = 20;
  bool hasMore = true;
  bool isLoading = false;

  @override
  void onReady() async {
    super.onReady();

    final args = Get.arguments;
    userId.value = args["userId"];
    friendId.value = args["friendId"];
    friendAvatar.value = args["friendAvatar"];
    friendName.value = args["friendName"];

    UserModel? user = await Storage().getUser();
    userAvatar.value = user?.avator ?? "";

    if (args["targetMessageId"] != null && args["targetMessageId"] != 0) {
      targetMessageId.value = args["targetMessageId"];
      SchedulerBinding.instance.addPostFrameCallback((_) async {
        await _targetMessages();
      });
    } else {
      SchedulerBinding.instance.addPostFrameCallback((_) async {
        await _loadMessages(refresh: true);
        if (scrollController.hasClients) scrollController.jumpTo(0);
      });
    }
  }

  /// ✅ 下拉刷新（加载上一页消息）
  Future<void> onRefresh() async {
    print("📩 下拉刷新");
    if (pageNum > 1) {
      pageNum--;
      await _loadMessages(isPull: true);
    }
    refreshController.resetNoData();
    refreshController.refreshCompleted();
  }

  /// ✅ 上拉加载更多（加载下一页）
  Future<void> onLoading() async {
    print("📨 上拉加载更多");

    if (!hasMore) {
      refreshController.loadNoData();
      return;
    }

    pageNum++;
    await _loadMessages();

    if (hasMore) {
      refreshController.loadComplete();
    } else {
      refreshController.loadNoData();
    }
  }

  /// ✅ 加载消息（分页）
  Future<void> _loadMessages({bool refresh = false, bool isPull = false}) async {
    if (isLoading) return;
    isLoading = true;

    try {
      if (refresh) {
        pageNum = 1;
        hasMore = true;
      }

      print("📃 当前请求页码：$pageNum");

      final response = await HttpService.to.get(
        "/user-message/query",
        query: {"userId": userId.value, "friendId": friendId.value, "pageNum": pageNum, "pageSize": pageSize},
      );

      if (response.statusCode == 200 && response.data["code"] == 200) {
        final List<dynamic> records = response.data["data"]["records"] ?? [];
        List<UserMessageModel> messages = [];

        // ✅ 使用 for 循环打印每条消息内容
        for (var e in records) {
          var msg = UserMessageModel.fromJson(e);
          print("消息ID: ${msg.id}, 内容: ${msg.content}, 时间: ${msg.sendTime}");
          messages.add(msg);
        }

        if (refresh) {
          userMessageList.assignAll(messages);
        } else {
          if (isPull) {
            // ✅ 保持滚动位置不跳动
            double oldOffset = scrollController.offset;

            userMessageList.insertAll(0, messages);

            await Future.delayed(Duration(milliseconds: 0));
            if (scrollController.hasClients) {
              double estimatedHeight = 80.0 * messages.length;
              scrollController.jumpTo(oldOffset + estimatedHeight);
            }
          } else {
            userMessageList.addAll(messages);
          }
        }

        hasMore = messages.length == pageSize;
      }

      update(["chatdetail"]);
    } catch (e) {
      print("❌ 加载消息失败：$e");
    } finally {
      isLoading = false;
    }
  }

  /// ✅ 根据 targetMessageId 定位到目标消息
  Future<void> _targetMessages() async {
    if (targetMessageId.value == 0) return;

    print("📍 查找目标消息 ID: ${targetMessageId.value}");

    bool found = false;
    int searchPage = 1;
    const int maxTry = 50;
    int tryCount = 0;

    while (!found && hasMore && tryCount < maxTry) {
      tryCount++;

      final response = await HttpService.to.get(
        "/user-message/query",
        query: {"userId": userId.value, "friendId": friendId.value, "pageNum": searchPage, "pageSize": pageSize},
      );

      if (response.statusCode == 200 && response.data["code"] == 200) {
        final List<dynamic> records = response.data["data"]["records"] ?? [];
        final messages = records.map((e) => UserMessageModel.fromJson(e)).toList();

        final index = messages.indexWhere((m) => m.id == targetMessageId.value);

        if (index != -1) {
          print("✅ 找到目标消息在第 $searchPage 页 第 $index 条");

          pageNum = searchPage;
          userMessageList.assignAll(messages);
          found = true;

          await Future.delayed(const Duration(milliseconds: 150));
          SchedulerBinding.instance.addPostFrameCallback((_) {
            if (scrollController.hasClients) {
              final position = index * 80.0;
              scrollController.jumpTo(position);
            }
          });
        } else {
          if (messages.length < pageSize) {
            hasMore = false;
          } else {
            searchPage++;
          }
        }
      } else {
        hasMore = false;
      }
    }

    if (!found) print("⚠️ 未找到目标消息 ID: ${targetMessageId.value}");
  }

  /// ✅ 发送消息
  void sendMessage() async {
    final text = textController.text.trim();
    if (text.isEmpty) return;

    try {
      final response = await HttpService.to.post(
        "/user-message/sendMessage",
        data: {"senderId": userId.value, "receiverId": friendId.value, "content": text, "type": 1},
      );

      if (response.statusCode == 200 && response.data["code"] == 200) {
        final userMessageModel = UserMessageModel.fromJson(response.data["data"]);
        userMessageList.insert(0, userMessageModel);
      } else {
        userMessageList.insert(
          0,
          UserMessageModel(
            id: DateTime.now().millisecondsSinceEpoch,
            senderId: userId.value,
            receiverId: friendId.value,
            content: text,
            type: MessageType.text,
            sendTime: DateTime.now(),
            readStatus: 0,
          ),
        );
      }

      textController.clear();
      update(["chatdetail"]);

      SchedulerBinding.instance.addPostFrameCallback((_) {
        if (scrollController.hasClients) {
          scrollController.animateTo(0.0, duration: const Duration(milliseconds: 250), curve: Curves.easeOut);
        }
      });
    } catch (e) {
      print("❌ 发送消息异常：$e");
    }
  }

  /// ✅ 接收消息（实时）
  Future<void> receiveMessage(UserMessageModel userMessage) async {
    userMessageList.insert(0, userMessage);
    SchedulerBinding.instance.addPostFrameCallback((_) {
      if (scrollController.hasClients) {
        scrollController.animateTo(0.0, duration: const Duration(milliseconds: 250), curve: Curves.easeOut);
      }
    });
  }
}
